package com.example.archivemanagement.controller;

import com.example.archivemanagement.audit.AuditEvent;
import com.example.archivemanagement.audit.AuditEventProducer;
import com.example.archivemanagement.service.HdfsService;
import com.example.archivemanagement.utils.SparkUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/hdfs")
@CrossOrigin(origins = "*", maxAge = 3600)
public class HdfsController {

    @Autowired
    private HdfsService hdfsService;

    @Autowired
    private AuditEventProducer auditEventProducer;


    @PostMapping("/upload")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<?> uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam("hdfsPath") String hdfsPath) {

        Map<String, String> map = hdfsService.uploadFile(file, hdfsPath);
        AuditEvent event = new AuditEvent("upload Hdfs",
                UUID.randomUUID().toString(), "上传 Hdfs",
                SparkUtils.getCurrentUsername(), LocalDateTime.now(), "");

        auditEventProducer.sendAuditEvent(event);
        return ResponseEntity.ok(map);
    }

    @GetMapping("/view")
    public ResponseEntity<?> viewFile(String fileName) {
        Map<String, String> map = hdfsService.viewFile(fileName);

        AuditEvent event = new AuditEvent("查看 Hdfs",
                UUID.randomUUID().toString(), "查看 Hdfs",
                SparkUtils.getCurrentUsername(), LocalDateTime.now(), "");

        auditEventProducer.sendAuditEvent(event);
        return ResponseEntity.ok(map);
    }

    @GetMapping("/download")
    public ResponseEntity<byte[]> download(@RequestParam String fileName) {
        try {
            // 解码前端传递的文件名
            String decodedFileName = URLDecoder.decode(fileName, "utf-8");
            String content = hdfsService.download(decodedFileName);

            // 配置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.TEXT_PLAIN);
            headers.setContentDisposition(ContentDisposition.attachment()
                    .filename(decodedFileName, StandardCharsets.UTF_8)
                    .build());

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(content.getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(("下载失败: " + e.getMessage()).getBytes());
        }
    }
}
